//
//  BIDUserInputViewController.m
//  随手记01
//
//  Created by 邵瑞 on 13-5-1.
//  Copyright (c) 2013年 邵瑞. All rights reserved.
//

#import "BIDUserInputViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "BIDDateView.h"
#import "BIDPinViewController.h"
#import "DatePicker.h"
#import "BIDABill.h"
#import "BIDBillsManager.h"
#import "BIDDatabaseManager.h"
#import "BIDClockVC.h"
#import "BIDDeleteBill.h"
#import "BIDModifyView.h"
#import "BIDUserSaveToInternet.h"
#import "BIDTypesManager.h"
#define kStateComponent 0
#define kZipComponent 1
#define kisEqual @"类型选择>>"
#define kSpendMoney 1
#define kIncomeMoney 0
@interface BIDUserInputViewController ()
{
	   DatePicker *dp;
    BIDTypesManager *typeManager;
       BIDBillsManager * billsMannager;
    UIButton * typeCaclePacker;
    NSInteger whichWay;
     NSString * setUp ;
    
}
@property(strong,nonatomic) NSMutableArray *typeName;
@property(strong,nonatomic) NSMutableArray *subTypeOfType;
@property (strong,nonatomic) UIButton * selectTimeButton;

@property(strong,nonatomic) ZenTextField *spendingMoney;
@property(strong,nonatomic)  ZenKeyboard *keyBoard;
@end

@implementation BIDUserInputViewController
@synthesize Singlebillplist =_Singlebillplist;
@synthesize selectTypeButton = _selectTypeButton;
@synthesize spendingDescription = _spendingDescription;
//类型学择
@synthesize PickerDict = _PickerDict;
@synthesize PickerTypeKeyA = _PickerTypeKeyA;
@synthesize PickerTypeValueB = _PickerTypeValueB;
@synthesize typePicker = _typePicker;
//时间选择
@synthesize typeName,subTypeOfType;
-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden=NO;
         UIBarButtonItem * back = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:0 target:self action:@selector(backUpPage)];
       self.navigationItem.leftBarButtonItem
        = back;

    [self initNavView];
}
-(void)viewWillDisappear:(BOOL)animated
{
       UISegmentedControl *con=(UISegmentedControl*)[self.navigationController.navigationBar viewWithTag:100];
       [con removeFromSuperview];

}
-(void)initNavView
{
    UISegmentedControl *con=[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"收入",@"支出", nil]];
    con.tag=100;
    
    con.tintColor=[UIColor grayColor];
    con.segmentedControlStyle=1;
    [con setSelectedSegmentIndex:1];
    _spendingMoney.textColor = [UIColor redColor];
    whichWay=1;
    con.frame = CGRectMake(100, 5, 120, 35);
    [con addTarget:self action:@selector(switchControl:) forControlEvents:UIControlEventValueChanged];
    [self.navigationController.navigationBar addSubview:con];

}
-(void)switchControl:(id)sender
{
   UISegmentedControl *con=sender;
   switch (con.selectedSegmentIndex)
   {
  case 0:
    whichWay=kIncomeMoney;
    _spendingMoney.textColor = [UIColor greenColor];
    break;
  case kSpendMoney:
    whichWay=kSpendMoney;
    _spendingMoney.textColor =[UIColor redColor];
    break;

  default:
    break;
}
}
- (void)viewDidLoad
{


      
              dp.subview.hidden=NO;
              typeCaclePacker = [[UIButton alloc] initWithFrame:CGRectMake(235, 200, 82, 33)];
              [typeCaclePacker setBackgroundColor:[UIColor clearColor]];
              [typeCaclePacker setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
              [typeCaclePacker setTitle:@"取消类型选择" forState:UIControlStateNormal];
              typeCaclePacker.titleLabel.font = [UIFont systemFontOfSize:13];
              [typeCaclePacker addTarget:self action:@selector(keyboardtodisappear:) forControlEvents:UIControlEventTouchUpInside];
              [self.view addSubview:typeCaclePacker];
              typeCaclePacker.hidden  = YES;
              _typePicker.hidden = YES;
              [self.typePicker setBackgroundColor:[UIColor brownColor]];
              typeManager=[BIDTypesManager shareTypesManager];
              billsMannager = [BIDBillsManager shareBillsManager];
              self.typeName=[typeManager DatabaseHadTypes];
              if (self.typeName.count!=0) {
                 NSInteger number=[[self.typeName objectAtIndex:0] integerValue];
                 self.subTypeOfType=[typeManager listOfSubTypeInMainType:number];
           }
    
              //金额
              _spendingMoney=[[ZenTextField alloc] initWithFrame:CGRectMake(100, 10, 154, 30)];
              _spendingMoney.delegate=self;
              _keyBoard=[[ZenKeyboard alloc] initWithFrame:CGRectMake(0, 0, 325, 205)];
              _keyBoard.textField=_spendingMoney;
              _spendingMoney.textAlignment=NSTextAlignmentRight;
              _spendingMoney.inputView=_keyBoard;
              _spendingMoney.borderStyle = 2;
              _spendingMoney.backgroundColor=[UIColor clearColor];
              [_spendingMoney becomeFirstResponder];
              //时间选择
              self.selectTimeButton = [[UIButton alloc] initWithFrame:CGRectMake(100, 130, 194, 60)];
              [self.selectTimeButton setBackgroundColor:[UIColor clearColor]];
              dp =[[DatePicker alloc]initWithFrame:self.selectTimeButton.frame];
             // [dp setDate:[NSDate date]];
              dp.datePickerMode=UIDatePickerModeDate;
              
              [self.view addSubview:self.selectTimeButton];
              NSString * str  = dp.textField.text;
              dp.textField.backgroundColor = [UIColor clearColor];
              [self.selectTimeButton setTitle:str forState:UIControlStateNormal];
              [self.view addSubview:dp];
       

              [self.view addSubview:_spendingMoney];
               [self.typePicker setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"picker.png"]]];
              [self.view setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"jiyibi.png"]]];
       [_spendingDescription setBackgroundColor:[UIColor clearColor]];

       _spendingDescription.delegate =self;
       _spendingDescription.keyboardType = UIReturnKeyDefault;
       [_spendingDescription.layer setCornerRadius:12 ];
       [_spendingDescription.layer setBorderWidth:3];
       [_spendingDescription.layer setBorderColor:[UIColor grayColor].CGColor];
       _spendingDescription.returnKeyType = UIReturnKeyDone;

    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
 UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"记一笔" style:0 target:self action:@selector(saveabillbutton:)];
       
//self.tabBarController.navigationItem.leftBarButtonItem = item;
//       UIBarButtonItem *a=[[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:nil];
       //whichWay=kIncomeMoney;
//    [a view].tag=100;
    NSLog(@"%@",self.navigationItem.rightBarButtonItem);
    self.navigationItem.rightBarButtonItem=item;

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -
#pragma mark Picker Data Source Methods
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == kStateComponent)
    {
        return [self.typeName count];
      

    }
    else
    {
        return [self.subTypeOfType count];
 
    }
}
#pragma  mark Picker Delegate Methods
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == kStateComponent)
    {
        NSString *str=[typeManager selectTypeName:[[self.typeName objectAtIndex:row] integerValue]];
        return str;
    }
    else
    { 
        BIDATypes *type=[self.subTypeOfType objectAtIndex:row];
        NSString *str=[typeManager selectSubTypeName:type.subTypeId];
        return str;
    }

}
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component ==kStateComponent)
    {
      NSInteger number=[[self.typeName objectAtIndex:row] integerValue];
        
        self.subTypeOfType = [typeManager listOfSubTypeInMainType:number];
        [self.typePicker selectRow:0 inComponent:kZipComponent animated:YES];
        [self.typePicker reloadComponent:kZipComponent];
    }
}
-(CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
{
    return 50;
}
-(CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
   return  140;
}
- (void)dealloc
{
    [_spendingDescription release];
    
    [_typePicker release];
    [_selectTypeButton release];
       [_buttons release];
       [_SetButon release];
       [_lookbuton release];
       [_managerbuton release];
    [super dealloc];
}
- (void)viewDidUnload
{
    [self setTypePicker:nil];
    [self setSpendingDescription:nil];
    [self setTypePicker:nil];
    [self setSelectTypeButton:nil];
    [super viewDidUnload];
}
-(IBAction)keyboardtodisappear:(id)sender;
{



       UIButton * s0 =  (UIButton *)[self.view viewWithTag:100];
       UIButton *s1 = (UIButton *)[self.view viewWithTag:101];
             UIButton * s2 = (UIButton *)[self.view viewWithTag:102];
             UIButton* s3 = (UIButton *)[self.view viewWithTag:103];


            s0.hidden = NO;
              s1.hidden = NO;
            s2.hidden = NO;
            s3.hidden = NO;


            
    _typePicker.hidden = YES;
	if (_spendingMoney.enabled)
	 {
	   [_spendingMoney setEnabled:NO];
	   }
   else
   {
   	[_spendingMoney setEnabled:YES];

   }

	_keyBoard.hidden=YES;
	dp.textField.hidden=NO;
	_selectTypeButton.hidden = NO;
    BIDABill *CopyData = [[BIDABill alloc] init];
    NSString *spendDesrcs = self.spendingDescription.text;
    if (self.typeName.count!=0) {
        
    
    NSInteger stateRow =[self.typePicker selectedRowInComponent:kStateComponent];
    NSInteger zipRow = [self.typePicker selectedRowInComponent:kZipComponent];
        NSArray * ss  = nil;
    NSInteger  select = [[self.typeName objectAtIndex:stateRow] integerValue];
           CopyData.CtypeAndSubtype = [ss objectAtIndex:0];
    NSString *selectType = [typeManager selectTypeName:select];
    ss=[selectType componentsSeparatedByString:@"--"];
    if (ss.count==0)
    {
       CopyData.CtypeAndSubtype = [ss objectAtIndex:0];
       
       }
    NSInteger selectsub  =[[self.subTypeOfType objectAtIndex:zipRow] subTypeId];
    
    NSString *selectSubtype = [typeManager selectSubTypeName:selectsub];
    NSString *message = [[NSString alloc] initWithFormat:@"%@--%@",selectType,selectSubtype];
       [self.selectTypeButton setTitle:message forState:UIControlStateNormal];
    NSString *spendTypes  =  self.selectTypeButton.titleLabel.text;
    NSString *spendTime = _selectTimeButton.titleLabel.text;
    CopyData.Camount = self.spendingMoney.text.floatValue;//
    CopyData.Cdescription =spendDesrcs ;
     CopyData.CtypeAndSubtype = spendTypes;
    CopyData.Ctime = spendTime;    
    self.Singlebillplist = [[NSMutableArray alloc] init];
    [self.Singlebillplist addObject:CopyData];
    [self.spendingMoney resignFirstResponder];
        [self.spendingDescription resignFirstResponder];}
	if (!_keyBoard)
	 {
	   _keyBoard.hidden = YES;
	   }
    typeCaclePacker.hidden = YES;
    [sender resignFirstResponder];
}

-(void)saveabillbutton:(id)sender
{

	_selectTypeButton.hidden = NO;
	BOOL judge = [self judgeStringWhetherNil];
	   if (!judge)
	   {

	   NSLog(@"不能插入数据");
	   }
	   
	    
}

-(BOOL)judgeStringWhetherNil
{

       if (  self.spendingMoney.text.length==0 ||
       _selectTimeButton.titleLabel.text.length == 0  )
       {
       // self.spendingDescription.text.length == 0 ||

              UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"请完整填写" delegate:self cancelButtonTitle:@"两秒钟之后自动消失" otherButtonTitles:nil];
              alert.delegate = self;
              [alert setBackgroundColor:[UIColor redColor]];
              [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(dismAlter:) userInfo:alert repeats:NO];
              [alert show];
              [alert release];

       }
       else if (self.spendingMoney.text.length!=0 && self.spendingMoney.text!=nil &&self.selectTypeButton.titleLabel.text.length!=0&&
       _selectTimeButton.titleLabel.text.length != 0 && _selectTimeButton.titleLabel.text !=nil)
       {
       //  self.spendingDescription.text.length != 0 && self.spendingDescription.text !=
              [self saveabille];
              if ([self.selectTypeButton.titleLabel.text isEqualToString:kisEqual])
              {

              

              }
              else
              {
                     UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提醒" message:@"帐单记录成功" delegate:self cancelButtonTitle:@"两秒钟之后自动消失" otherButtonTitles:nil];
                     alert.delegate = self;
                     [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(dismAlter:) userInfo:alert repeats:NO];
                     [alert show];
                     [alert release];
                     _spendingDescription.text = nil;
                     _spendingMoney.text = nil;
                     self.selectTypeButton.titleLabel.text = @"类型选择>>";
                     
                     NSDateFormatter * s =[[NSDateFormatter alloc] init];
                     [s  setDateFormat:@"yyyy-MM-dd hh:mm:ss +0800"];
//                     [s setDateFormat:@"dd/MM/yyyy hh:mmaaa"];
                     NSDate * dates = [NSDate date];
                     [dp setDate:dates];
                     NSString * time = [s stringFromDate:dates];
              //[self.selectTimeButton setTitle:@"" forState:UIControlStateNormal];
                 dp.textField.text=time;
                  //   [self.selectTimeButton setTitle:time forState:UIControlStateNormal];

//                     self.selectTimeButton.titleLabel.text = time;
                     NSLog(@"当前的时间是:%@",time);

              }


       }
       return YES;

}

- (IBAction)selectTypePicker:(id)sender
{

       UIButton * s0 =  (UIButton *)[self.view viewWithTag:100];
       UIButton *s1 = (UIButton *)[self.view viewWithTag:101];
       UIButton * s2 = (UIButton *)[self.view viewWithTag:102];
       UIButton* s3 = (UIButton *)[self.view viewWithTag:103];

             s0.hidden = YES;
              s1.hidden = YES;
            s2.hidden = YES;
            s3.hidden = YES;
           self.typePicker.hidden = NO;
           typeCaclePacker.hidden = NO;
           NSInteger stateRow =[self.typePicker selectedRowInComponent:kStateComponent];
           NSInteger zipRow = [self.typePicker selectedRowInComponent:kZipComponent];
    if (self.typeName.count!=0) {
        
    
           NSInteger  select = [[self.typeName objectAtIndex:stateRow] integerValue];
           NSString *selectType = [typeManager selectTypeName:select];
           NSInteger selectsub  =[[self.subTypeOfType objectAtIndex:zipRow] subTypeId];
           NSString *selectSubtype = [typeManager selectSubTypeName:selectsub];
           NSString *message = [[NSString alloc] initWithFormat:@"%@--%@",selectType,selectSubtype];
        [self.selectTypeButton setTitle:message forState:UIControlStateNormal];}
}
-(void) selecttime
{
       NSString * str  = dp.textField.text;
    [_selectTimeButton setTitle:str forState:UIControlStateNormal];//UIControlEventValueChanged
}


- (IBAction)golookUp:(id)sender
{
	UITabBarController *bar=[[UITabBarController alloc] init];
    BIDDateView *bew=[[BIDDateView alloc] init];
    bew.view.backgroundColor = [UIColor whiteColor];
    BIDPinViewController * pinView = [[BIDPinViewController alloc] init];
//    pinView.view.backgroundColor = [UIColor brownColor];
    bar.viewControllers=[NSArray arrayWithObjects:bew,pinView, nil];
    bew.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"时间" image:nil tag:0];
    pinView.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"饼图" image:nil tag:0];
    [self Tranlayer];
    [self.navigationController pushViewController:bar animated:YES];

}


-(void)saveabille
{
	   _typePicker.hidden = YES;
    BIDABill *CopyData = [[BIDABill alloc] init];	
    NSString *spendDesrcs = self.spendingDescription.text;
    NSString *spendTypes  =  self.selectTypeButton.titleLabel.text;
	NSArray * array = nil;
	if ([self.selectTypeButton.titleLabel.text isEqualToString:kisEqual])
	 {
	   UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"警告" message:@"请选择类别" delegate:self cancelButtonTitle:@"两秒钟之后自动消失" otherButtonTitles: nil];
		
			  alert.delegate = self;
			  [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(dismAlter:) userInfo:alert repeats:NO];
			  [alert show];
			  return;

	   }
	   else
	   {
			  
              array = [spendTypes componentsSeparatedByString:@"--"];
			  NSString * maintypestr = [array objectAtIndex:0];
			  NSString * subtypestr = [array objectAtIndex:1];
			  CopyData.type_ID = [typeManager selectTypeid:maintypestr];
			  CopyData.subType_ID = [typeManager selectSubTypeid:subtypestr];
	   }

    NSString * spendTime =dp.textField.text;
    CopyData.Camount = _spendingMoney.text.floatValue;//;
    CopyData.Cdescription = spendDesrcs;
    CopyData.CtypeAndSubtype = spendTypes;
//	   NSString * maintypestr = [array objectAtIndex:0];
//    NSString * subtypestr = [array objectAtIndex:1];
//    CopyData.type_ID = [typeManager selectTypeid:maintypestr];
//    CopyData.subType_ID = [typeManager selectSubTypeid:subtypestr];
    NSArray *timearray = [spendTime componentsSeparatedByString:@"+"];
    NSString *timestr = [timearray objectAtIndex:0];
    CopyData.Ctime = timestr;
    CopyData.whichWay=whichWay;
    self.Singlebillplist = [[NSMutableArray alloc] init];
    [self.Singlebillplist addObject:CopyData];
    BOOL insrtabill = [billsMannager insertAPayout:CopyData];
    if (insrtabill) 
    {
        NSLog(@"插入成功");
    }
	   
}

- (IBAction)goClock:(id)sender
 {
 BIDClockVC * goclock =[[BIDClockVC alloc] init];
 [self.navigationController pushViewController:goclock animated:YES];
}

- (IBAction)goManager:(id)sender
{
       UITabBarController *bar=[[UITabBarController alloc] init];

          BIDDeleteBill *delete=[[BIDDeleteBill alloc] init];
          delete.view.backgroundColor = [UIColor whiteColor];
          BIDModifyView * modify = [[BIDModifyView alloc] init];

          bar.viewControllers=[NSArray arrayWithObjects:delete,modify, nil];

			delete.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"帐单的管理" image:nil tag:1];
			  modify.tabBarItem=[[UITabBarItem alloc] initWithTitle:@"类别管理" image:nil tag:1];       
			[self.navigationController pushViewController:bar animated:YES];
              
                        NSLog(@"处理数据");

}

- (IBAction)goSetUP:(id)sender
{
       BIDUserSaveToInternet * go = [[BIDUserSaveToInternet alloc] init];
       setUp = @"设置";
       [self Tranlayer];
       [self.navigationController pushViewController:go animated:YES];
       [go release];
}
#pragma  mark ---textFeild
-(void)textFieldDidBeginEditing:(UITextField *)textField
{
	   _keyBoard.hidden=NO;

       dp.textField.hidden = YES;
              
       
       }
-(void)textFieldDidEndEditing:(UITextField *)textField
{
                dp.textField.hidden = NO;

}
#pragma TextViewDelegate
-(void)textViewDidBeginEditing:(UITextView *)textView
{
       self.typePicker.hidden= YES;
       dp.textField.hidden = YES;
}
-(void)textViewDidEndEditing:(UITextView *)textView
{      dp.textField.hidden = NO;
       
}
-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
        if ([text isEqualToString:@"\n"])
         {

        [textView resignFirstResponder];

        return NO;

    }  

    return YES;  

}
#pragma NSTimer UIAletrVew ----delegate
-(void)dismAlter:(NSTimer *)time
{
    UIAlertView *alter=[time userInfo];
	[alter dismissWithClickedButtonIndex:0 animated:YES];
	[time invalidate];
}
-(void)backUpPage
{
       [self Tranlayer];
       [self.navigationController popViewControllerAnimated:YES];
}
-(void)Tranlayer
{
         CATransition * tran=[CATransition animation];
       tran.delegate =self;
       tran.duration = 1.5;
       tran.type = @"rippleEffect";
       tran.subtype = @"fromRight";
       UIView * view = self.navigationController.view;
       [view.layer addAnimation:tran forKey:@"vbdb"];

}
@end
